<?php
namespace app\api\controller\v1;
use think\admin\Controller;
use think\Response;
use app\data\model\DataBreed;
use app\data\model\DataGender;
use app\data\model\DataCat;
use app\data\model\DataCatCase;
use app\data\model\DataCatRemarks;
use app\data\model\DataCatLog;
use app\data\model\DataDeviceLog;
use app\data\model\DataDeviceCatGroup;
use app\data\model\DataDevice;
use app\data\service\IotThingService;
/**
 * 宠物数据接口
 * @class Pet
 * @package app\api\controller\v1
 *
 */
class Pet extends Controller
{
    public function del_group_cate(){
        $iotId = input('post.iotId');
        $catIds = input('post.catIds');
        DataDeviceCatGroup::mk()
            ->where('member_id',$this->request->uid)->where('iotId',$iotId)->where('catId','in',$catIds)
            ->delete();
        $this->success('删除成功');
    }
    public function add_group_cate(){
        $iotId = input('post.iotId');
        $catIds = input('post.catIds');
        foreach ($catIds as $v){
            DataDeviceCatGroup::mk()->insert([
                'member_id'=>$this->request->uid,
                'iotId'=>$iotId,
                'catId'=>$v
            ]);
        }
        $this->success('添加成功');
    }
    function get_group(){
        $member_id = $this->request->uid;
        $group = DataDevice::mk()->field('iotId,nickname')->where(['is_deleted'=>0,'member_id'=>$member_id])
            ->filter(function($item) {
                $cats_id = DataDeviceCatGroup::mk()->where(['iotId'=>$item['iotId'],'is_deleted'=>0])->column('catId');
                $item['cats'] = DataCat::mk()->getList([['c.id','in',$cats_id]],20);
                $item['current']=-1;
                $item['disabled']=false;
                return $item;
            })
            ->select();
        $this->success('获取成功',$group);
    }
    function check_weight(){
        $id = input('post.id/d');
        $weight = input('post.weight');
        $member_id = $this->request->uid;
        $weight_setting = sysconf('about.weight_min_max');
        $start_weight = $weight*1000-$weight_setting;
        $end_weight = $weight*1000+$weight_setting;
        $map[]=['member_id','=',$member_id];
        if($id!=''){
            $map[]=['id','<>',$id];
        }
        $count = DataCat::mk()->where($map)
            ->where('weight','between',[$start_weight,$end_weight])
            ->count();
        $this->success('获取成功',$count>0?true:false);
    }
    function getGroup($cat_id){
        return DataDeviceCatGroup::mk()->alias('g')->field('d.iotId,d.nickname')
            ->join('data_device d','d.iotId = g.iotId')
            ->where(['g.catId'=>$cat_id])->select();
    }
    //宠物详情
    function get(){
        $id = input('get.id/d');
        $res = DataCat::mk()->alias('c')->field('c.*,b.breed_name,g.gender_name')
            ->join('data_breed b','b.id = c.breed')
            ->join('data_gender g','g.id = c.gender')
            ->filter(function($item) {
                $item['state'] = 0;
                $item['weight'] = $item['weight']/1000;
                $item['group'] = $this->getGroup($item['id']);
                return $item;
            })
            ->where(['c.id'=>$id,'c.is_deleted'=>0])->find();
        $this->success('获取成功',$res);
    }
    //删除宠物
    function del(){
        $id = input('post.id');
        $res = DataCat::mk()->where(['id'=>$id])->update(['is_deleted'=>1]);
        //上传昵称缩略图排序到设备
        $info = DataCat::mk()->field('nickname,avatar_thumb,sort,weight,member_id')->find($id);
        $this->send_cat_info($info,1);
        $this->success('删除成功');
    }
    //修改头像
    function avatar(){
        $id = input('post.id');
        $thumb='';
        if(input('post.avatar')!=''){
            $avatar = input('post.avatar');
            $path = parse_url($avatar,PHP_URL_PATH);
            $thumb = './upload/thumb/'.uniqid().'.jpg';
            compressedImage($path,$thumb);
        }
        $res = DataCat::mk()->where(['id'=>$id])->update(['avatar'=> input('post.avatar'),'avatar_thumb'=>$thumb]);
        $this->success('修改成功',$res);
    }
    //我的宠物
    public function my()
    {
        $member_id = $this->request->uid;
        $map[]=['member_id','=',$member_id];
        $res = DataCat::mk()->getList($map);
        $this->success('获取成功',$res);
    }
    //宠物列表 分页
    public function get_list()
    {
        $member_id = $this->request->uid;
        $res = DataCat::mk()->alias('c')->field('c.*,b.breed_name,g.gender_name')
            ->join('data_breed b','b.id = c.breed')
            ->join('data_gender g','g.id = c.gender')
            ->filter(function($item) {
                $item['state'] = 0;
                $item['group'] = $this->getGroup($item['id']);
                return $item;
            })
            ->where(['c.member_id'=>$member_id,'c.is_deleted'=>0])->order('c.id asc')->paginate(20);
        $this->success('获取成功',$res);
    }
    //宠物品种
    public function breed()
    {
        $data = DataBreed::mk()->field('id,breed_name as name,photo as avatar')
            ->where(['is_deleted'=>0])->order('sort asc,id asc')->select()->toArray();
        $res = groupByInitials($data,'name');
        $arr=[];
        $arr1=[];
        foreach($res as $k =>$v){
            $arr['letter']=$k;
            $arr['data']=$v;
            array_push($arr1,$arr);
        }
        $hot = DataBreed::mk()->field('id,breed_name as name,photo as avatar')
            ->where(['is_deleted'=>0,'is_tj'=>1])->order('sort asc,id asc')->select()->toArray();
        $res['data']=$arr1;
        $res['hot']=$hot;
        $this->success('获取成功',$res);
    }
    //宠物性别
    public function gender()
    {
        $data = DataGender::mk()->field('id,gender_name as name,photo as cover,color')
            ->where(['is_deleted'=>0])->order('sort asc,id asc')->select()->toArray();

        $this->success('获取成功',$data);
    }
    //编辑宠物
    public function save(){
        $data = input('post.');
        $data['weight']=$data['weight']*1000;
        $photos = $data['bingli_photos'];
        $content =$data['bingli_text'];
        $remark =$data['remark'];
        $device_ids = $data['select_device'];
        unset($data['bingli_photos']);
        unset($data['bingli_text']);
        unset($data['select_device']);
        unset($data['remark']);
        if(isset($data['id'])){
            //编辑宠物信息
            $cat = DataCat::mk()->find($data['id']);
            if($data['avatar']!='' && $cat['avatar']!=$data['avatar']){
                $avatar = $data['avatar'];
                $path = parse_url($avatar,PHP_URL_PATH);
                $thumb = './upload/thumb/'.uniqid().'.jpg';
                compressedImage('.'.$path,$thumb);
                $data['avatar_thumb']=$thumb;
            }
            DataCat::mk()->update($data);
            //绑定设备
            DataDeviceCatGroup::mk()->where(['catId'=>$data['id']])->delete();//删除绑定数据，重新绑定
            if(!empty($device_ids)){
                $device_data=[];
                foreach($device_ids as $v){
                    $device_data[]=[
                        'member_id'=>$this->request->uid,
                        'catId'=>$data['id'],
                        'iotId'=>$v
                    ];
                }
                DataDeviceCatGroup::mk()->insertAll($device_data);
            }
            $id = $data['id'];
        }else{
            $data['member_id']=$this->request->uid;
            //排序1-8
            $sort = DataCat::mk()->where(['member_id'=>1,'is_deleted'=>0])
                ->order('sort asc')
                ->group('sort')->having('sort > 0')
                ->column('sort');
            $array=[1,2,3,4,5,6,7,8];
            $missing=[];
            foreach($array as $v){
                if(!in_array($v, $sort)){
                    $missing[] = $v;
                }
            }
            $data['sort'] = empty($missing)?0:min($missing);

            //设置缩略图
            if($data['avatar']!=''){
                $path = parse_url($data['avatar'],PHP_URL_PATH);
                $thumb = './upload/thumb/'.uniqid().'.jpg';
                compressedImage('./'.$path,$thumb);
                $data['avatar_thumb']=$thumb;
            }
            $id =DataCat::mk()->insertGetId($data);
            //绑定设备
            if(!empty($device_ids)){
                $device_data=[];
                foreach($device_ids as $v){
                    $device_data[]=[
                        'member_id'=>$this->request->uid,
                        'catId'=>$id,
                        'iotId'=>$v
                    ];
                }
                DataDeviceCatGroup::mk()->insertAll($device_data);
            }
            //上传病例
            if($content!='' || count($photos)>0){
                $bl_data=[
                    'cat_id'=>$id,
                    'photos'=>count($photos)>0?json_encode($photos):'',
                    'content'=> $content
                ];
                DataCatCase::mk()->insert($bl_data);
            }
            //添加备注
            if($remark!=''){
                $remark_data=[
                    'cat_id'=>$id,
                    'content'=> $remark
                ];
                DataCatRemarks::mk()->insert($remark_data);
            }
        }
        //上传昵称缩略图排序到设备
        $info = DataCat::mk()->field('nickname,avatar_thumb,sort,weight,member_id')->find($id);
        $msg = $this->send_cat_info($info);
        $this->success('保存成功',$id);
    }
    function set_pet_info($iotId,$title,$value){
        $class = new IotThingService();
        $item = '{"'.$title.'":'.$value.'}';
        $res = $class->setProp($iotId,$item);
        if($res['err_code'] == 0){
            $response = $res['data'];
            if($response->body->code !=''){
                $this->error($response->body->code);
            }else{
                if($title == 'Light'){
                    $value_arr = json_decode($value,true);
                    $key = key($value_arr);
                    if($key == 'Switch_Toggle'){
                        $remark = '灯光颜色自动切换:'.($value_arr['Switch_Toggle']==1?'开启':'关闭');
                        $log_data=[
                            'iot_id'=>$iotId,
                            'remark'=>$remark
                        ];
                        DataDeviceLog::mk()->insert($log_data);
                    }elseif ($key == 'Switch1_Not_Disturb'){
                        $remark =  '灯光勿扰1:'.($value_arr['Switch1_Not_Disturb']==1?'开启':'关闭');
                        $log_data=[
                            'iot_id'=>$iotId,
                            'remark'=>$remark
                        ];
                        DataDeviceLog::mk()->insert($log_data);
                    }elseif ($key == 'Switch2_Not_Disturb'){
                        $remark =  '灯光勿扰2:'.($value_arr['Switch2_Not_Disturb']==1?'开启':'关闭');
                        $log_data=[
                            'iot_id'=>$iotId,
                            'remark'=>$remark
                        ];
                        DataDeviceLog::mk()->insert($log_data);
                    }
                }
                $this->success('success',json_decode($response->body->data->messageId,true));
            }
        }else{
            $this->error($res['data']);
        }
    }
    //病例列表
    public function get_case_list(){
        $cat_id = input('get.cat_id/d');
        $res = DataCatCase::mk()
            ->where(['cat_id'=>$cat_id,'is_deleted'=>0])
            ->filter(function($item) {
                $item['photos'] = json_decode($item['photos'],true);
                return $item;
            })
            ->paginate(10);
        $this->success('获取成功',$res);
    }
    //保存病例
    public function save_case(){
        $data = input('post.');
        if(isset($data['id'])){
            unset($data['cat_id']);
            $data['photos'] = json_encode($data['photos']);
            DataCatCase::mk()->update($data);
        }else{
            $data['member_id']=$this->request->uid;
            $data['photos'] = json_encode($data['photos']);
            DataCatCase::mk()->save($data);
        }
        $this->success('保存成功');
    }
    //病例详情
    public function get_case(){
        $id = input('get.id/d');
        $res = DataCatCase::mk()
            ->filter(function($item) {
                $item['photos'] = json_decode($item['photos'],true);
                return $item;
            })
            ->where(['id'=>$id,'is_deleted'=>0])->find();
        $this->success('获取成功',$res);
    }
    //删除病例
    public function del_case(){
        $id = input('post.id/d');
        $res = DataCatCase::mk()->where(['id'=>$id])->update(['is_deleted'=>1]);
        $this->success('获取成功',$res);
    }
    //备注列表
    public function get_remark_list(){
        $cat_id = input('get.cat_id/d');
        $res = DataCatRemarks::mk()
            ->where(['cat_id'=>$cat_id,'is_deleted'=>0])
            ->paginate(10);
        $this->success('获取成功',$res);
    }
    //保存备注
    public function save_remark(){
        $data = input('post.');
        if(isset($data['id'])){
            unset($data['cat_id']);
            DataCatRemarks::mk()->update($data);
        }else{
            $data['member_id']=$this->request->uid;
            DataCatRemarks::mk()->save($data);
        }
        $this->success('保存成功');
    }
    //备注详情
    public function get_remark(){
        $id = input('get.id/d');
        $res = DataCatRemarks::mk()
            ->where(['id'=>$id,'is_deleted'=>0])->find();
        $this->success('获取成功',$res);
    }
    //删除备注
    public function del_remark(){
        $id = input('post.id/d');
        $res = DataCatRemarks::mk()->where(['id'=>$id])->update(['is_deleted'=>1]);
        $this->success('获取成功',$res);
    }
    //如厕日志
    function get_toilet_log(){
        $type = input('get.type'); //today,week,month
        $cat_id = input('get.id');
        if($type == 0){
            $res = DataCatLog::mk()->alias('l')->field('l.*,c.nickname,c.avatar,date_format(l.in_time, "%m-%d") as day,date_format(l.in_time, "%H:%i") as time')
                ->leftjoin('data_cat c','c.id = l.cat_id')
                ->where(['l.cat_id'=>$cat_id])->whereDay('l.in_time')
                ->order('l.in_time desc')
                ->paginate(10)->toArray();
        }else{
            $days = $type == 1?7:90;
            $start_time =   date("Y-m-d",strtotime("-{$days} day"))." 00:00:00";
            $end_time =   date("Y-m-d H:i:s");
            $res = DataCatLog::mk()->alias('l')->field('l.*,c.nickname,c.avatar,date_format(l.in_time, "%m-%d") as day,date_format(l.in_time, "%H:%i") as time')
                ->leftjoin('data_cat c','c.id = l.cat_id')
                ->where(['l.cat_id'=>$cat_id])
                ->whereTime('l.in_time', '<=', $end_time)
                ->whereTime('l.in_time', '>=', $start_time)
                ->order('l.in_time desc')
                ->paginate(10)->toArray();
        }
        $this->success('获取成功',$res);
    }
    function get_weight_log(){
        $type = input('get.type'); //today,week,month
        $cat_id = input('get.id');
        if($type == 0){
            $res = DataCatLog::mk()->alias('l')
                ->field('l.*,c.nickname,c.avatar')
                ->leftjoin('data_cat c','c.id = l.cat_id')
                ->where(['l.cat_id'=>$cat_id])->whereDay('l.in_time')
                ->filter(function($item) {
                    $item['compare'] = 0;
                    return $item;
                })
                ->order('l.in_time desc')
                ->paginate(10)->toArray();
        }else{
            $days = $type == 1?7:30;
            $start_time =   date("Y-m-d",strtotime("-{$days} day"))." 00:00:00";
            $end_time =   date("Y-m-d H:i:s");
            $res = DataCatLog::mk()->alias('l')
                ->field('l.*,c.nickname,c.avatar')
                ->leftjoin('data_cat c','c.id = l.cat_id')
                ->where(['l.cat_id'=>$cat_id])
                ->whereTime('l.in_time', '<=', $end_time)
                ->whereTime('l.in_time', '>=', $start_time)
                ->order('in_time desc')
                ->filter(function($item) {
                    $item['compare'] = 0;
                    return $item;
                })
                ->paginate(10)->toArray();
        }
        $this->success('获取成功',$res);
    }
    function send_cat_info($info,$del=0){
        $msg=[];
        if($info['sort']>0){
            $iotIds = DataDevice::mk()->where(['member_id'=>$info['member_id'],'status'=>1])->column('iotId');
            $weight = round($info['weight']/1000, 2);
            $avatar_thumb =$info['avatar_thumb'];
            $class = new IotThingService();
            $data=[
                'Cat_ID'=>$info['sort'],
                'Cat_Name'=>$info['nickname'],
                'Cat_Weight'=>$weight,
                'Cat_Picture_Size'=>$avatar_thumb==''?0:filesize($avatar_thumb),
                'Cat_Picture'=>$avatar_thumb==''?'':config('iot.host').str_replace('./', '/', $avatar_thumb),
                'Del_ID'=>$del,
            ];
            foreach($iotIds as $k=> $v){
                $res = $class->setService($v,'Cat_Data',json_encode($data));
                $msg[$k]=$res['data']->body->data;
                unset($res);
            }
            if($del==1){
                //补位
                $new_info = DataCat::mk()
                    ->field('id,nickname,avatar_thumb,sort,weight,member_id')
                    ->where(['member_id'=>$info['member_id'],'is_deleted'=>0,'sort'=>0])
                    ->order('id asc')
                    ->find()->toArray();
                DataCat::mk()->where(['id'=>$new_info['id']])->update(['sort'=>$info['sort']]);
                if(!empty($new_info)){
                    $new_info['sort']=$info['sort'];
                    $this->send_cat_info($new_info,0);
                }
            }
        }
        return $msg;
    }
}
